import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'AdminLogin',
    component: () => import('@/views/AdminLogin.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/Main.vue'),
    redirect: '/agents',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/models',
        name: 'Models',
        component: () => import('@/views/Models.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/tools',
        name: 'Tools',
        component: () => import('@/views/Tools.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/agents',
        name: 'Agents',
        component: () => import('@/views/Agents.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/hot-tools',
        name: 'HotTools',
        component: () => import('@/views/HotTools.vue'),
        meta: { requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('admin_token')
  
  // 需要登录的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      ElMessage.warning('请先登录')
      next('/login')
    } else {
      next()
    }
  } else {
    // 已登录用户访问登录页，跳转到首页
    if (to.path === '/login' && token) {
      next('/agents')
    } else {
      next()
    }
  }
})

export default router

